import React from "react";
import imgCat from '../static/cat.png';
// 高阶组件
function withMouse(WrappedComponent) {
    // 该组件提供复用得状态逻辑
    class Mouse extends React.Component {
        // 鼠标状态
        state = {
            x: 0,
            y: 0
        }
        handleMouse = (e) => {
            this.setState({
                x: e.clientX,
                y: e.clientY,
            });
        }
        componentDidMount() {
            window.addEventListener('mouseover', this.handleMouse);
        }
        componentWillUnmount() {
            window.removeEventListener('mouseover', this.handleMouse);
        }
        render() {
            return <WrappedComponent {...this.state}></WrappedComponent>
        }
    }

    // 设置displayName
    Mouse.displayName = `WithMouse${getDisplayName(WrappedComponent)}`

    return Mouse
}
// 设置displayName得具体方法
function getDisplayName(WrappedComponent) {
    return WrappedComponent.displayName || WrappedComponent.name || 'Component'
}



// 用来测试高阶组件
const Postion = props =>
(
    <p>
        鼠标位置变化 ：（x:{props.x}，y:{props.y}）
    </p>
)


const Cat = props => (
    <img src={imgCat} alt="猫咪" style={{
        position: "absolute",
        left: props.x - 250,
        top: props.y - 215
    }} />
)

// 获取增强后得组件
const MousePostion = withMouse(Postion);

// 复用 组件例子
const MouseCat = withMouse(Cat);

class HeightRender extends React.Component {
    render() {
        return (
            <div>
                <h1>高阶组件</h1>
                {/* 渲染我们增强后得组件 */}
                <MousePostion></MousePostion>
                {/* 复用组件例子 */}
                <MouseCat></MouseCat>
            </div>
        )
    }
}

export default HeightRender